package com.bocai.dahuatech.ui.frag;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.PersonInfoBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseFragment;
import com.bocai.dahuatech.ui.activity.ChangePsdActivity;
import com.bocai.dahuatech.ui.activity.LoginActivity;
import com.bocai.dahuatech.ui.activity.MyAddressActivity;
import com.bocai.dahuatech.ui.activity.MyCollectionActivity;
import com.bocai.dahuatech.ui.activity.MyExchangeActivity;
import com.bocai.dahuatech.ui.activity.MyOrderListActivity;
import com.bocai.dahuatech.ui.activity.NewMyPointActivity;
import com.bocai.dahuatech.ui.activity.ProfilesActivity;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.BitmapUtil;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.RZUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 我的主界面
 */
public class Fragment_Me extends BaseFragment implements View.OnClickListener{
    private View view;
    @Bind(R.id.swipe_me)
    SwipeRefreshLayout swipeMe;
    @Bind(R.id.title_tv)
    TextView mTitleTv;
    @Bind(R.id.ll_me_order)
    LinearLayout llMeOrder;
    @Bind(R.id.ll_me_point)
    LinearLayout llMePoint;
    @Bind(R.id.ll_me_exchange)
    LinearLayout llMeExchange;
    @Bind(R.id.ll_me_collection)
    LinearLayout llMeCollection;
    @Bind(R.id.ll_me_profiles)
    LinearLayout llMeProfiles;
    @Bind(R.id.ll_me_setpsd)
    LinearLayout llMeSetpsd;
    @Bind(R.id.ll_me_certification)
    LinearLayout llMeCertification;
    @Bind(R.id.ll_me_address)
    LinearLayout llMeAddress;
//    @Bind(R.id.ll_me_about)
//    LinearLayout llMeAbout;
    @Bind(R.id.tv_me_nickname)
    TextView tvNickName;
    @Bind(R.id.tv_me_viptype)
    TextView tvVIPType;
    @Bind(R.id.civ_me_photo)
    CircleImageView civPhoto;
    @Bind(R.id.tv_exitlogin)
    TextView tvExitLogin;
    PersonInfoBean bean=new PersonInfoBean();
    ArrayList<String> photos;
    private String photo;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.mefrag, container, false);
        initView(view);
        return view;
    }
    private void initView(View view) {
        ButterKnife.bind(this,view);
        mTitleTv.setText(R.string.me);
        getData();
        initEvent();
    }
    Observer<BaseBean> observer=new Observer<BaseBean>(){

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

            Log.e("erro",e.toString());
            swipeMe.setRefreshing(false);
            showToast(R.string.neterror);
            hideLoading();
        }

        @Override
        public void onNext(BaseBean baseBean) {
            hideLoading();
            swipeMe.setRefreshing(false);
            if("1".equals(baseBean.getReturnNo()))
            {
                String result= AESUtils.decode(baseBean.getContent());
                Log.e("result",result);
                bean=new Gson().fromJson(result, PersonInfoBean.class);
                tvNickName.setText(bean.getLoginName());
                if(bean.getMemberType()==7)
                {
                    tvVIPType.setText(R.string.personvip);
                }else
                {
                    tvVIPType.setText(R.string.distributorvip);
                }
                Glide.with(getActivity())
                        .load(bean.getAvatar())
                        .error(R.mipmap.user_photo_defalt)
                        .into(civPhoto);
            }else{
                showError(baseBean.getReturnInfo());
            }
        }
    };

    /**
     * 获取会员信息
     */
    private void getData()
    {
        int id=SharePrefencesUtil.getFID(getActivity());
        getTestApi().getPersonInfo(id)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void initEvent()
    {
        llMeOrder.setOnClickListener(this);
        llMePoint.setOnClickListener(this);
        llMeExchange.setOnClickListener(this);
        llMeCollection.setOnClickListener(this);
        llMeProfiles.setOnClickListener(this);
        llMeSetpsd.setOnClickListener(this);
        llMeCertification.setOnClickListener(this);
        llMeAddress.setOnClickListener(this);
//        llMeAbout.setOnClickListener(this);
        civPhoto.setOnClickListener(this);
        tvExitLogin.setOnClickListener(this);
        swipeMe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
        if (data != null) {
            photos =
                    data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
            civPhoto.setImageBitmap(BitmapUtil.compressBitmap(photos.get(0)));
            new MyAsyncTask().execute();

        }
//        }
    }
    /**
     * 生成该类的对象，并调用execute方法之后
     * 首先执行的是onProExecute方法
     * 其次执行doInBackgroup方法
     *
     */
    class MyAsyncTask extends AsyncTask<Integer, Integer, String> {


        public MyAsyncTask() {
            super();
        }


        /**
         * 这里的Integer参数对应AsyncTask中的第一个参数
         * 这里的String返回值对应AsyncTask的第三个参数
         * 该方法并不运行在UI线程当中，主要用于异步操作，所有在该方法中不能对UI当中的空间进行设置和修改
         * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作
         */
        @Override
        protected String doInBackground(Integer... params) {
            Bitmap bitmap = BitmapFactory.decodeFile(photos.get(0));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 30, baos);
            try
            {
                baos.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            byte[] buffer = baos.toByteArray();
            photo = Base64.encodeToString(buffer, 0, buffer.length, Base64.DEFAULT);
            return photo;
        }
        /**
         * 这里的String参数对应AsyncTask中的第三个参数（也就是接收doInBackground的返回值）
         * 在doInBackground方法执行结束之后在运行，并且运行在UI线程当中 可以对UI空间进行设置
         */
        @Override
        protected void onPostExecute(String result) {
            uploadPhoto(photo);
//            personInfoPresenter.upLoadPhoto(photo, "jpg");
        }
    }

    private void uploadPhoto(String photo) {
        showLoading();
        getTestApi().uploadPhoto(SharePrefencesUtil.getFID(getActivity()),"data:image/png;base64,"+photo)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observerPhoto);
    }

    Observer<BaseBean> observerPhoto=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
        }

        @Override
        public void onNext(BaseBean baseBean) {
            hideLoading();
            showToast(baseBean.getReturnInfo());
            civPhoto.setImageBitmap(BitmapFactory.decodeFile(photos.get(0)));
        }
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.tv_exitlogin:
                //退出当前登录
                DialogUtil.dialogForTwoButton(getActivity(), R.string.areyousureexit, R.string.dismiss, R.string.exit, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharedPreferences preferences = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putInt("fid", -1);
                        editor.putString("user_id", "");
                        editor.putString("FUserName", "");
                        editor.putString("customerCode", "");
                        editor.putString("customerName", "");
                        editor.putInt("FAccessFlag", -1);
                        editor.putString("Province", "");
                        editor.putString("City", "");
                        editor.putString("Area", "");
                        editor.putBoolean("isremember", false);
                        editor.commit();
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        getActivity().finish();
                        DialogUtil.dismissTowDialog();
                    }
                });

                break;
            case R.id.civ_me_photo:
                //修改图像
                PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
                intent.setPhotoCount(1);
                intent.setShowCamera(true);
                startActivityForResult(intent, 1000);
                break;
            case R.id.ll_me_order:
                //我的订单
                if(SharePrefencesUtil.getFAccessFlag(getActivity())==0)//游客 去登录
                {
                    {
                        DialogUtil.dialogForTwoButton(getActivity(), R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.putExtra("tologin", false);
                                startActivity(intent);
                                DialogUtil.dismissTowDialog();
                            }
                        });
                    }
                }
                else if(SharePrefencesUtil.getFAccessFlag(getActivity())!=2) //个人  去认证
                {
                    DialogUtil.dialogForTwoButton(getActivity(), R.string.notseeorder, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(getActivity())==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(getActivity(),R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(getActivity())==7)
                            {
                                RZUtil.renZheng(getActivity());
//                                Intent intent1=new Intent(getActivity(),RegistDistributorSecendActivity.class);
//                                IndividualBean bean=new IndividualBean();
//                                intent1.putExtra("register",bean);
//                                intent1.putExtra("what", "certifiled");
//                                startActivity(intent1);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }else
                {

                    startActivity(new Intent(getActivity(),MyOrderListActivity.class));
                }
                break;
            case R.id.ll_me_point:
                //我的华积分
                if(SharePrefencesUtil.getFAccessFlag(getActivity())==0)//游客 去登录
                {
                    {
                        DialogUtil.dialogForTwoButton(getActivity(), R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.putExtra("tologin", false);
                                startActivity(intent);
                                DialogUtil.dismissTowDialog();
                            }
                        });
                    }
                }
                else if(SharePrefencesUtil.getFAccessFlag(getActivity())!=2) //个人  去认证
                {
                    DialogUtil.dialogForTwoButton(getActivity(), R.string.notseepoint, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(getActivity())==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(getActivity(),R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(getActivity())==7)
                            {
                                RZUtil.renZheng(getActivity());
//                                Intent intent1=new Intent(getActivity(),RegistDistributorSecendActivity.class);
//                                IndividualBean bean=new IndividualBean();
//                                intent1.putExtra("register",bean);
//                                intent1.putExtra("what", "certifiled");
//                                startActivity(intent1);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }else
                {

                    startActivity(new Intent(getActivity(),NewMyPointActivity.class));
                }
                break;
            case R.id.ll_me_exchange:
                //我的兑换
                if(SharePrefencesUtil.getFAccessFlag(getActivity())==0)//游客 去登录
                {
                    {
                        DialogUtil.dialogForTwoButton(getActivity(), R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.putExtra("tologin", false);
                                startActivity(intent);
                                DialogUtil.dismissTowDialog();
                            }
                        });
                    }
                }
                else if(SharePrefencesUtil.getFAccessFlag(getActivity())!=2) //个人  去认证
                {
                    DialogUtil.dialogForTwoButton(getActivity(), R.string.notseeexchange, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(getActivity())==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(getActivity(), R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(getActivity())==7)
                            {
                                RZUtil.renZheng(getActivity());
//                                Intent intent1=new Intent(getActivity(),RegistDistributorSecendActivity.class);
//                                IndividualBean bean=new IndividualBean();
//                                intent1.putExtra("register",bean);
//                                intent1.putExtra("what", "certifiled");
//                                startActivity(intent1);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }else
                {
                    startActivity(new Intent(getActivity(),MyExchangeActivity.class));
                }
                break;
            case R.id.ll_me_collection:
                //我的收藏
                startActivity(new Intent(getActivity(),MyCollectionActivity.class));
                break;
            case R.id.ll_me_address:
                //我的收货地址
                if(SharePrefencesUtil.getFAccessFlag(getActivity())==0)//游客 去登录
                {
                    {
                        DialogUtil.dialogForTwoButton(getActivity(), R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.putExtra("tologin", false);
                                startActivity(intent);
                                DialogUtil.dismissTowDialog();
                            }
                        });
                    }
                }
                else if(SharePrefencesUtil.getFAccessFlag(getActivity())!=2) //个人  去认证
                {

                    DialogUtil.dialogForTwoButton(getActivity(), R.string.notseeaddress, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if(SharePrefencesUtil.getFAccessFlag(getActivity())==6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(getActivity(), R.string.alreadysubmitdata,R.string.know);
                            }else  if(SharePrefencesUtil.getFAccessFlag(getActivity())==7)
                            {
                                RZUtil.renZheng(getActivity());
//                                Intent intent1=new Intent(getActivity(),RegistDistributorSecendActivity.class);
//                                IndividualBean bean=new IndividualBean();
//                                intent1.putExtra("register",bean);
//                                intent1.putExtra("what", "certifiled");
//                                startActivity(intent1);
                                DialogUtil.dismissTowDialog();
                            }
                        }
                    });
                }else
                {
                    Intent intent3=new Intent(getActivity(),MyAddressActivity.class);
                    intent3.putExtra("what","list");
                    startActivity(intent3);
                }
                break;
            case R.id.ll_me_profiles:
                //个人中心
                Intent intent2=new Intent(getActivity(),ProfilesActivity.class);
                intent2.putExtra("data",bean);
                startActivity(intent2);
                break;
            case R.id.ll_me_setpsd:
                //修改密码
                startActivity(new Intent(getActivity(),ChangePsdActivity.class));
                break;
            case R.id.ll_me_certification:
                //分销商认证
                if(SharePrefencesUtil.getFAccessFlag(getActivity())==2)
                {
                    DialogUtil.dialogForOneButton(getActivity(),R.string.isdistributor,R.string.know);
                }else if(SharePrefencesUtil.getFAccessFlag(getActivity())==6)
                {
                    DialogUtil.dismissTowDialog();
                    DialogUtil.dialogForOneButton(getActivity(), R.string.alreadysubmitdata, R.string.know);
                }else  if(SharePrefencesUtil.getFAccessFlag(getActivity())==7)
                {
                    RZUtil.renZheng(getActivity());
//                    Intent intent1 = new Intent(getActivity(), RegistDistributorSecendActivity.class);
//                    IndividualBean bean = new IndividualBean();
//                    intent1.putExtra("register", bean);
//                    intent1.putExtra("what", "certifiled");
//                    startActivity(intent1);
                    DialogUtil.dismissTowDialog();

                }
                break;

        }
    }
}
